package com.android.sharecar.activity;

import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.android.sharecar.model.User;

/**
 * class:SignupStep2Activity
 *  Deals with the signup transactions,
 *  include user's real name, mobile phone and 
 *  head picture.
 * @date:	2011-9-8
 * @author xinyan
 * 
 */
public class SignupStep2Activity extends Activity {
	public static final String TAG = "SignupStep2Activity";

	// member vars
	private EditText mRealName; // var for real name edit text
	private EditText mMobilePhone; // var for mobile phone edit text
	private RadioGroup mGender; // var for gender radio group
	private ImageView mHeadPicture; // var for head picture
	private Button mFinish; // var for next button

	public static User user;

	// constants
	public static final String ALERT_TYPE_ILLEGAL_REALNAME = "illegal realname";
	public static final String ALERT_TYPE_ILLEGAL_MOBILEPHONE = "illgal phone number";
	public static final String ALERT_TYPE_EMPTY = "haven't input";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.signup2);

		mRealName = (EditText) findViewById(R.id.signup_et_realName);
		mMobilePhone = (EditText) findViewById(R.id.signup_et_mobilePhone);
		mGender = (RadioGroup) findViewById(R.id.signup_rg_gender);
		mHeadPicture = (ImageView) findViewById(R.id.signup_iv_headPicture);
		mFinish = (Button) findViewById(R.id.signup_btn_finish);

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		user = (User) bundle.get("user");
		if (null == user) {
			Log.v(TAG, "receive user object from step1 failed!");
		} else {
			Log.v(TAG, "receive user object from step1 succeed.");
		}

		mGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (R.id.signup_rb_male == checkedId) {
					user.setGender("男");
				} else if (R.id.signup_rb_female == checkedId) {
					user.setGender("女");
				}
			}
		});

		mHeadPicture.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				if (MotionEvent.ACTION_DOWN == event.getAction()) {

					// get head picture
					Intent getPicture = new Intent();
					getPicture.setType("image/*");
					getPicture.setAction("android.intent.action.GET_CONTENT");
					startActivityForResult(getPicture, 1);

					return true;
				}
				return false;
			}
		});

		mFinish.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String strRealName = mRealName.getText().toString();
				String strMobilePhone = mMobilePhone.getText().toString();

				if (strMobilePhone.equals("") || strRealName.equals("")) {
					AlertDialog alertEmpty = creatBuilder(ALERT_TYPE_EMPTY)
							.create();
					alertEmpty.show();

					return;
				} else { // else user have input the info perfectly
					if (!checkMobilePhone(strMobilePhone)) {
						AlertDialog alertIllegalPhoneNum = creatBuilder(
								ALERT_TYPE_ILLEGAL_MOBILEPHONE).create();
						alertIllegalPhoneNum.show();

						return;
					} else {
						user.setMobilePhone(strMobilePhone);
					}

					if (!checkRealName(strRealName)) {
						AlertDialog alertIllegalRealName = creatBuilder(
								ALERT_TYPE_ILLEGAL_REALNAME).create();
						alertIllegalRealName.show();

						return;
					} else {
						user.setRealName(strRealName);
					}

					// upload signup info onto the server.
					// this function will be finished in the following project
					// steps.

				} // end of else - user have input the info perfectly
			} // end of onClick
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri uri = data.getData();
			ContentResolver cr = this.getContentResolver();

			Log.v(TAG, "The result picture uri:" + uri.toString());

			try {
				Bitmap bitmap = BitmapFactory.decodeStream(cr
						.openInputStream(uri));

				/* 将Bitmap设定到ImageView */
				mHeadPicture.setImageBitmap(bitmap);
				user.setHeadPicture(bitmap);
			} catch (FileNotFoundException e) {
				Log.e(TAG, "FileNotFoundException, message:" + e.getMessage());
			}
		}// end of if resultcode ==
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Builder creator
	 * used for create all kinds of warning dialog in this
	 * activity
	 * 
	 * @param type
	 *            alert type, constants listed on the top area.
	 * @return return a builder
	 */
	private AlertDialog.Builder creatBuilder(String type) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				SignupStep2Activity.this);
		builder.setTitle("警告");
		if (ALERT_TYPE_EMPTY == type) {
			builder.setMessage("请您输入完整的注册信息！");
		} else if (ALERT_TYPE_ILLEGAL_MOBILEPHONE == type) {
			builder.setMessage("您输入的手机号格式不正确，请重新输入！");
		} else if (ALERT_TYPE_ILLEGAL_REALNAME == type) {
			builder.setMessage("您输入的姓名格式不正确，请重新输入！");
		}

		builder.setPositiveButton("确定", null);

		return builder;
	}

	/**
	 * check whether the real name is illegal or not.
	 * @param realName real name
	 * @return return true if legal, or return false.
	 */
	private boolean checkRealName(String realName) {
		return realName.matches("^[\u4e00-\u9fa5]+$") && realName.length() <= 6;
	}

	/**
	 * check whether the phone number is legal or not.
	 * @param phoneNumber phone number
	 * @return return true if legal, or return false.
	 */
	private boolean checkMobilePhone(String phoneNumber) {
		/*String strReg = "^([0-9]{3}-?[0-9]{8})|([0-9]{4}-?[0-9]{7})$";
		Pattern p = Pattern.compile(strReg);

		// 创建一个Matcher，并进行精确匹配
		Matcher m = p.matcher(phoneNumber);
		return m.matches();*/
		return phoneNumber.matches("^[1][3,5]+\\d{9}");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

}
